<script setup>
// 只能被调用，父组件传参
import { computed, watch } from "vue";
import { useRouter } from "vue-router"
import dayjs from 'dayjs'
const router = useRouter()
const props = defineProps(['username'])

const userName = ref(''), userData = ref({})
const isMe = computed(() => userName.value.toLowerCase() == User.name.toLowerCase()) // 是否是当前用户

// 数据源：props.username
watch(() => props.username, v => {
  if (v) userName.value = v
  else userName.value = User.name
}, { immediate: true })

watch(userName, (v, ov) => {
  if (v != ov) {
    // 用户名变了，全部重制
    User.getUserdata(userName.value, data => userData.value = data)
  }
}, { immediate: true })

const logout = User.userLogout
</script>

<template>
  <!-- 顶部用户模块 -->
  <div class="usermodel model">
    <!-- 有用户的DIV -->
    <div v-if="userName">
      <!-- 头像 -->
      <div class="userimg">
        <img class="tx"
          :src="userData.userImg || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
      </div>

      <!-- 用户名 -->
      <div class="username">{{ userData.userName }}</div>

      <!-- 用户信息 -->
      <div class="info">
        <div>{{ userData?.userInfo?.userText }}</div>
        <div>
          <span class="userid">UID: {{ userData.userId }}</span>
        </div>
        <div>
          <span class="userbirth">生日:
            {{ dayjs(userData.userInfo?.userBirth).format("YYYY-MM-DD") }}
          </span>&nbsp;&nbsp;
          <span class="usersex">性别:
            <span>{{ userData.userSex || "未知" }}</span>
          </span>
        </div>
      </div>

      <div v-if="isMe" class="btn">
        <el-button text @click="router.push('/release')">发个博客</el-button>
        <el-button text @click="logout">退出登录</el-button>
      </div>

    </div>

    <div v-else>
      <div class="userimg">
        <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" class="tx" />
      </div>
      <el-button text @click="router.push('/login')" class="username">请先登录</el-button>
    </div>
  </div>
  <!-- {{ userData }} -->
</template>

<style lang="less" scoped>
.usermodel {
  position: relative;
  text-align: center;
  overflow: visible; // 会导致filter偏移

  .userimg {
    transition: 0.5s;
    position: absolute;
    top: 15px;
    left: 50%;
    overflow: hidden;
    transform: translate(-50%, -50%);

    img {
      border-radius: 50%;
      height: 150px;
      width: 150px;
      object-fit: cover;
    }
  }

  &:hover .userimg {
    top: 10px;
  }

  .username {
    margin-top: 70px;
    font-size: 35px;
    font-weight: bolder;
  }

  .info {
    line-height: 30px;
  }

  .btn {
    margin-top: 10px;
  }
}
</style>